package main

import (
	"fmt"
	"github.com/go-redis/redis"
	"runtime"
	"strconv"
	"strings"
	"time"
)

var (
	redisKey = "test_data"
)

/*用户公共可操作资源加锁*/
func main() {
	/*获取redis client*/
	rdb := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password set
		DB:       0,  // use default DB
	})
	nowTimeStamp := time.Now().Unix()
	result, err := rdb.Get(redisKey).Result()
	if err != redis.Nil {
		fmt.Println(result)
		/*取redis 值*/
	} else {
		ok := rdb.SetNX(fmt.Sprint(redisKey, "NX"), nowTimeStamp, time.Second*5).Val()
		//加锁成功
		if ok {
			/*TODO 去查数据库相关操作*/
			//防止误删
			if value := rdb.Get(fmt.Sprint(redisKey, "NX")).Val(); value == strconv.Itoa(int(nowTimeStamp)) {
				rdb.Del(fmt.Sprint(redisKey, "NX"))
			}
		}
		//并发阻塞
		index := 0

		for {
			result, err = rdb.Get(redisKey).Result()
			if err != redis.Nil {
				fmt.Println(result)
				break
			}

			if index > 10 {
				break
			}
			index++
			time.Sleep(time.Millisecond * 300)
		}
	}
	/*TODO 处理返回数据*/
}

/*用户个人数据（用户个人修改） 采用旁路缓存模式*/
/*
http option get  : 第一次get设置缓存 后面取缓存
http option del/update : 删除缓存
*/

func GetCurrentGoroutineId() int {
	buf := make([]byte, 128)
	buf = buf[:runtime.Stack(buf, false)]
	stackInfo := string(buf)

	goIdStr := strings.TrimSpace(strings.Split(strings.Split(stackInfo, "[running]")[0], "goroutine")[1])
	goId, err := strconv.Atoi(goIdStr)
	if err != nil {
		fmt.Println("err=", err)
		return 0
	}
	return goId
}
